package com.haiyou.dc.message.util;

import com.haiyou.dc.message.constant.OpenfireConstant;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;


/**
 * @author pc
 */
@Slf4j
public class RedisUtils {

    private static JedisPool jedisPool = null;
    private static int db_index = 6;

    public static JedisPool init() {
        log.info("init jedis start.....");
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(30);
        config.setMaxIdle(2);
        config.setMaxWaitMillis(1000);
        config.setTestOnBorrow(true);
        jedisPool = new JedisPool(config, OpenfireConstant.HOST, OpenfireConstant.PORT, 1000, OpenfireConstant.AUTH, db_index);
        log.info("init jedis end host:{}:{},密码:{},DB={},jedisPool={}", OpenfireConstant.HOST, OpenfireConstant.PORT, OpenfireConstant.AUTH, db_index, jedisPool);
        return jedisPool;
    }

    public static Jedis getJedis() {
        if (jedisPool == null) {
            init();
        }
        Jedis resource = jedisPool.getResource();
        return resource;

    }

    public static void close(Jedis jedis) {
        try {
            if (jedis != null) {
                jedis.close();
            }
        } catch (Throwable e) {
            log.error("returnResource error ", e);
        }
    }

    public static Long saveSingleSession(String sender, String receiver) {
        log.info("saveSingleSession===>sender={},receiver=", sender, receiver);
        String prefixKey = "session_";
        long score = System.currentTimeMillis();
        Jedis jedis = getJedis();
        try {
            long result1 = jedis.zadd(prefixKey + sender, score, "userId_" + receiver);
            long result2 = jedis.zadd(prefixKey + receiver, score, "userId_" + sender);
            return result1 + result2;
        } catch (Throwable e) {
            log.error("sender={},receiver={},e={}", sender, receiver, e);
        } finally {
            close(jedis);
        }
        return null;
    }

    public static Long saveGroupSession(String sender, String groupName) {
        String key = "session_" + sender;
        Jedis jedis = getJedis();
        try {
            return jedis.zadd(key, System.currentTimeMillis(), "groupName_" + groupName);
        } catch (Throwable e) {
            log.error("sender={},groupName={},e={}", sender, groupName, e);
        } finally {
            close(jedis);
        }
        return null;
    }
}


